<template>
  <el-dialog
    fullscreen
    :title="title"
    :visible="open"
    append-to-body
    @close="onClose"
    @opened="onOpen"
  >
    <div class="exam-box" v-if="open">
      <div>
        <el-steps :active="active" finish-status="success">
          <el-step title="考试基本信息" />
          <el-step title="配置试卷" />
          <el-step title="发布" />
        </el-steps>
      </div>
      <div class="exam-body">
        <el-form ref="form" :model="form" label-width="120px">
          <div v-if="active == 0" class="exam-content">
            <el-card class="box-card">
              <el-form-item label="考试名称" prop="name">
                <el-input style="width:300px;" v-model="form.name" />
              </el-form-item>
              <el-form-item label="选择题单题分值" prop="chooseScore">
                <el-input-number
                  style="width:300px;"
                  v-model="form.chooseScore"
                />
              </el-form-item>
              <el-form-item label="填空题单题分值" prop="fillInTheBlankScore">
                <el-input-number
                  style="width:300px;"
                  v-model="form.fillInTheBlankScore"
                />
              </el-form-item>
              <el-form-item label="问答题单题分值" prop="otherScore">
                <el-input-number
                  style="width:300px;"
                  v-model="form.otherScore"
                />
              </el-form-item>
              <el-form-item label="答题人员选择" prop="otherScore">
                <el-button type="primary" @click="showUserSelect"
                  >选择</el-button
                >
                <div>{{ panNames }}</div>
              </el-form-item>
            </el-card>
          </div>
          <div v-if="active == 1" class="exam-content">
            <div class="exam-content-right">
              <div class="add-title">添加题目</div>
              <el-button
                plain
                class="type-btn"
                type="primary"
                @click="onAddQuestion(0)"
                >选择题</el-button
              >
              <el-button
                plain
                class="type-btn"
                type="primary"
                @click="onAddQuestion(1)"
                >填空题</el-button
              >
              <el-button
                plain
                class="type-btn"
                type="primary"
                @click="onAddQuestion(2)"
                >问答题</el-button
              >
            </div>

            <div class="exam-content-left">
              <div v-for="(item, index) in questions" :key="index">
                <!-- 选择题 -->
                <div v-if="item.type == 0" class="exam-item">
                  <div class="exam-item-title">
                    <div class="exam-no">{{ index + 1 }}.</div>
                    <el-input v-model="item.title" placeholder="请输入题目" />
                    <i
                      class="el-icon-delete"
                      @click="onDelQuestions(index)"
                    ></i>
                  </div>
                  <div>
                    <div class="exam-item-value">
                      <div
                        v-for="(option, idx) in item.option"
                        :key="idx"
                        class="exam-item-select"
                      >
                        <el-checkbox v-model="option.checked" label="复选框 A"
                          >选项{{ idx | filterIndexToABC }}</el-checkbox
                        >
                        <el-input
                          v-model="option.label"
                          placeholder="请输入选项"
                        />
                        <i
                          class="el-icon-delete"
                          style="cursor: pointer;color:red;"
                          @click="onDeloption(index, idx)"
                        ></i>
                      </div>
                    </div>
                    <el-button
                      type="primary"
                      icon="el-icon-circle-plus"
                      @click="onAddoption(index)"
                      >添加选项</el-button
                    >
                  </div>
                </div>

                <!-- 填空题 -->
                <div v-if="item.type == 1" class="exam-item">
                  <div class="exam-item-title">
                    <div class="exam-no">{{ index + 1 }}.</div>
                    <div>注：先选中正确答案，再插入填空符即可划线</div>
                    <i
                      class="el-icon-delete"
                      @click="onDelQuestions(index)"
                    ></i>
                    <!-- <el-button @click="onDelQuestions(index)">删除</el-button
                    >{{ index + 1 }} -->
                    <!-- <div placeholder="请输入题目" v-html="s" /> -->
                    <!-- <div @click.prevent="onAddEmptySign">插入填空符</div> -->
                    <!-- <div>注：先选中正确答案再插入填空符即可</div> -->
                  </div>
                  <Edit
                    v-if="open && active == 1"
                    :key="index"
                    toolbar="underline"
                    :open="open"
                    v-model="item.title"
                    :height="180"
                  />
                  <!-- <div v-html="item.title"></div> -->
                </div>
                <!-- 问答题 -->
                <div v-if="item.type == 2" class="exam-item">
                  <div class="exam-item-title">
                    <div class="exam-no">{{ index + 1 }}.</div>
                    <el-input
                      type="textarea"
                      v-model="item.title"
                      placeholder="请输入题目"
                    />
                    <i
                      class="el-icon-delete"
                      @click="onDelQuestions(index)"
                    ></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div v-if="active == 2" class="exam-content">
            <el-card class="box-card">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="考试时间" prop="times">
                    <el-date-picker
                      v-model="form.times"
                      type="datetimerange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="yyyy-MM-dd HH:mm:ss"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="答卷时长" prop="duration">
                    <el-radio-group v-model="form.timeType">
                      <el-radio :label="1"
                        ><el-input-number
                          v-model="form.duration"
                          style="width:150px;"
                        />分钟</el-radio
                      >
                      <el-radio :label="0">不限时长</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="答题次数" prop="frequency">
                    <el-input-number
                      :min="1"
                      :precision="0"
                      v-model="form.frequency"
                    />
                    <!-- <el-radio-group v-model="form.frequency">
                  <el-radio :label="1"><el-input v-model="form.count" />次</el-radio>
                  <el-radio :label="0">不限次数</el-radio>
                </el-radio-group> -->
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="考试说明" prop="remark">
                    <el-input
                      type="textarea"
                      v-model="form.remark"
                      style="width:400px;"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-card>
          </div>
        </el-form>
      </div>
      <div>
        <div class="exam-footer" style="text-align:center;">
          <el-button
            style="margin:0 20px;"
            v-if="active != 0"
            type="primary"
            @click="onPrevStep"
            >上一步</el-button
          >
          <el-button
            style="margin:0 20px;"
            type="primary"
            @click="onNextStep"
            :disabled="loading"
            >{{ active == 2 ? "发布" : "下一步" }}</el-button
          >
          <el-button style="margin:0 20px;" @click="$emit('close')"
            >关 闭</el-button
          >
        </div>
      </div>
    </div>
    <User
      :m1="m1"
      :m2="m2"
      :open="openUser"
      @close="openUser = false"
      @select="onSelectUser"
    />
  </el-dialog>
</template>

<script>
import {
  addExam,
  getExam,
  putExam,
  setExamPanIds,
  getExamPanIds
} from "../../../api/cms/exma";
import { batchRecord, startExam } from "../../../api/cms/record";
import Edit from "./edit";
import User from "./user";
// import Edit from "@/components/tinymce-editor"
// a.match(/<u[^>]*>([\s\S]*?)<\/u>/g)
// a.replace(/<u[^>]*>([\s\S]*?)<\/u>/g,"�")
const reg = /<u[^>]*>([\s\S]*?)<\/u>/g;
// const reg = /<span[^>]*>([\s\S]*?)<\/span>/g;

export default {
  components: { Edit, User },
  filters: {
    filterIndexToABC(index) {
      return String.fromCharCode(65 + index);
    }
  },
  props: {
    categoryId: {
      type: String | Number,
      default: ""
    },
    type: {
      type: Number,
      default: 0 // 0: 编辑 1: 预览 2: 考试
    },
    id: {
      type: String | Number,
      default: ""
    },
    open: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: "创建考试"
    }
  },
  data() {
    return {
      checkList: [],
      active: 0,
      form: {
        frequency: 1,
        chooseScore: "",
        fillInTheBlankScore: "",
        otherScore: "",
        name: "",
        startDate: "",
        endDate: "",
        duration: 50,
        timeType: 1,
        remark: ""
      },
      questions: [],
      openUser: false,
      panIds: [],
      panNames: "",
      loading: false,
      m1: [],
      m2: []
    };
  },
  created() {},
  methods: {
    onSelectUser(val, val2) {
      console.log(val, val2);
      this.m1 = val;
      this.m2 = val2;
      const list = [...val, ...val2].map(x => x.panId);
      this.panNames = [...val, ...val2].map(x => x.username).join(",");
      this.panIds = list;
    },
    showUserSelect() {
      this.openUser = true;
    },
    reset() {
      this.checkList = [];
      this.active = 0;
      this.form = {
        chooseScore: "",
        fillInTheBlankScore: "",
        otherScore: "",
        name: "",
        startDate: "",
        endDate: "",
        duration: 50,
        remark: ""
      };
      this.questions = [];
      this.panIds = [];
      this.panNames = "";
      this.m1 = [];
      this.m2 = [];
    },
    onClose() {
      this.reset();
      this.$emit("close");
    },
    onOpen() {
      if (!this.id) return;
      getExamPanIds(this.id).then(res => {
        res.data.forEach(x => {
          x.id = x.userId;
        });
        this.panIds = res.data.map(x => x.userId);
        this.panNames = res.data.map(x => x.userName).join(",");
        this.m1 = res.data.filter(x => x.type == 1);
        this.m2 = res.data.filter(x => x.type == 2);
      });
      getExam(this.id).then(response => {
        const questions = response.data.cmsExamQuestionList.map(x => {
          if (x.type == 0) {
            const answers = x.answer.split("�");
            const option = x.options.split("�").map(item => {
              return {
                label: item,
                checked: answers.indexOf(item) > -1 ? true : false
              };
            });
            return {
              id: x.id,
              type: 0, // 0 , 1, 2, 3
              title: x.title,
              option
            };
          }

          if (x.type == 1) {
            console.log(x.title);
            return {
              type: 1,
              title: x.title
            };
          }
          if (x.type == 2) {
            return {
              type: 2,
              title: x.title
            };
          }
        });
        this.questions = questions;

        response.data.times = [response.data.startDate, response.data.endDate];
        response.data.timeType = response.data.duration ? 1 : 0;
        this.form = response.data;

        if (this.type == 2) {
          this.onStartExam();
        }
      });
    },
    onStartExam() {
      startExam(this.id)
        .then(res => {
          this.$message.success("开始考试成功");
        })
        .catch(err => {
          this.$message.error("开始考试失败");
        });
    },
    onDelQuestions(index) {
      this.questions.splice(index, 1);
    },
    onAddQuestion(type) {
      this.questions.push({
        type,
        title: "",
        option: [
          {
            label: "",
            checked: false
          },
          {
            label: "",
            checked: false
          },
          {
            label: "",
            checked: false
          },
          {
            label: "",
            checked: false
          }
        ]
      });
    },
    onDeloption(index, idx) {
      if (this.questions[index].option.length <= 2) {
        this.$message.error("至少保留两个选项");
        return;
      }
      this.questions[index].option.splice(idx, 1);
    },
    onAddoption(index) {
      this.questions[index].option.push({
        label: "",
        checked: false
      });
    },
    onPrevStep() {
      this.active = this.active - 1;
    },
    onNextStep() {
      if (this.active == 0) {
        const {
          name,
          chooseScore,
          fillInTheBlankScore,
          otherScore
        } = this.form;

        if (!name) {
          this.$message.error("请输入考试名称");
          return;
        }
        if (chooseScore <= 0) {
          this.$message.error("请输入选择题单题分值");
          return;
        }
        if (fillInTheBlankScore <= 0) {
          this.$message.error("请输入填空题单题分值");
          return;
        }
        if (otherScore <= 0) {
          this.$message.error("请输入问答题单题分值");
          return;
        }
        if (this.panIds.length == 0) {
          this.$message.error("请选择考试人员");
          return;
        }
      }
      if (this.active == 1) {
        if (this.questions.length == 0) {
          this.$message.error("请添加题目");
          return;
        }
        if (this.questions.some(x => !x.title)) {
          this.$message.error("请填写题目");
          return false;
        }

        if (
          this.questions
            .filter(x => x.type === 0)
            .some(x => x.option.filter(y => y.checked && y.label).length < 1)
        ) {
          this.$message.error("请填写选项");
          return false;
        }

        if (
          this.questions
            .filter(x => x.type === 1)
            .some(y => !y.title.match(reg) || y.title.match(reg).length < 1)
        ) {
          this.$message.error("请划填空题答案");
          return false;
        }
      }

      if (this.active == 2) {
        const { times, timeType, duration } = this.form;

        if (!times || times.length <= 0) {
          this.$message.error("请选择考试时间");
          return;
        }

        if (timeType == 1 && duration <= 0) {
          this.$message.error("请输入考试时长");
          return;
        }
      }

      if (this.active == 2) {
        this.onSubmit();
      } else {
        this.active = this.active + 1;
      }
    },

    onSubmit() {
      // this.onJiaojuan();
      // return;

      this.questions
        .filter(x => x.type == 0)
        .forEach(x => {
          x.answer = [];
          x.option2 = [];
          x.option.forEach(y => {
            if (y.label) {
              x.option2.push(y.label);
              if (y.checked) {
                x.answer.push(y.label);
              }
            }
          });
        });
      this.questions
        .filter(x => x.type == 1)
        .forEach(x => {
          x.answer = x.title.match(reg).map(y => y.replace(reg, "$1"));
          x.option = x.title.replace(reg, "�");
        });

      const params = {
        ...this.form,
        startDate: this.form.times[0],
        endDate: this.form.times[1],
        cmsExamQuestionList: this.questions.map(x => {
          if (x.type == 0) {
            return {
              type: x.type,
              title: x.title,
              answer: x.answer.join("�"),
              options: x.option2.join("�"),
              score: this.form.chooseScore
            };
          } else if (x.type == 1) {
            return {
              type: x.type,
              title: x.title,
              answer: x.answer.join("�"),
              options: x.option,
              score: this.form.fillInTheBlankScore
            };
          } else if (x.type == 2) {
            return {
              type: x.type,
              title: x.title,
              answer: "",
              options: "",
              score: this.form.otherScore
            };
          }
        }),
        categoryId:this.categoryId
      };
      const count0 = this.questions.filter(x => x.type == 0).length;
      const count1 = this.questions.filter(x => x.type == 1).length;
      const count2 = this.questions.filter(x => x.type == 2).length;
      params.totalScore =
        params.chooseScore * count0 +
        params.fillInTheBlankScore * count1 +
        params.otherScore * count2;
      console.log(params);

      this.loading = true;
      if (this.id) {
        putExam(params).then(response => {
          setExamPanIds({ examId: this.id, panIds: this.panIds })
            .then(res => {
              this.loading = false;
              this.$emit("close2");
              this.$emit("success");
              this.$message.success("修改成功");
            })
            .catch(err => {
              this.loading = false;
            });
        });
        return;
      }

      addExam(params)
        .then(res => {
          if (res.code == 200) {
            setExamPanIds({ examId: res.data, panIds: this.panIds })
              .then(res => {
                this.loading = false;
                this.$emit("close2");
                this.$emit("success");
                this.$message.success("添加成功");
              })
              .catch(err => {
                this.loading = false;
              });
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
          this.loading = false;
        });
    },
    submitForm() {},
    cancel() {}
  }
};
</script>
<style lang="scss" scoped>
::v-deep {
  .el-dialog__body {
    height: calc(100% - 55px - 10px);
    box-sizing: border-box;
  }
}

.exam-box {
  display: flex;
  flex-direction: column;
  height: 100%;
  .exam-body {
    flex: 1;
    height: calc(100% - 60px);
    .el-form {
      height: 100%;
    }
  }
}
.exam-content {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  height: 100%;
  .exam-content-right {
    width: 200px;
    border-radius: 10px;
    border: 1px solid #ccc;
    padding: 20px;
    .type-btn {
      display: block;
      margin: 10px 0;
      width: 100%;
    }
    .add-title {
      color: #000;
      margin-bottom: 10px;
      font-weight: bold;
    }
  }
  .exam-content-left {
    flex: 1;
    margin: 0 20px;
    height: 100%;
    overflow-y: auto;
  }
}
.exam-item {
  border: 1px solid #bbb;
  border-radius: 10px;
  padding: 30px;
  margin-bottom: 20px;
  .exam-item-title {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .exam-no {
      font-size: 20px;
      margin-right: 10px;
    }
    i {
      color: red;
      margin-left: 10px;
      cursor: pointer;
    }
  }
  .exam-item-value {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  .exam-item-select {
    display: flex;
    align-items: center;
    width: 40%;
    margin-right: 10px;
    margin-bottom: 10px;
  }
}

.box-card {
  // margin: 50px 0;
  padding: 50px 0;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}
</style>
